package com.xjgzinfo.usdp.web.rest;

import com.xjgzinfo.usdp.constant.AuthConstant;
import com.xjgzinfo.usdp.core.domain.PageWapper;
import com.xjgzinfo.usdp.core.domain.ResponsePage;
import com.xjgzinfo.usdp.core.domain.ResponseResult;
import com.xjgzinfo.usdp.jpa.service.filter.BooleanFilter;
import com.xjgzinfo.usdp.jpa.service.filter.LongFilter;
import com.xjgzinfo.usdp.security.SecurityUtils;
import com.xjgzinfo.usdp.service.ImgAssetsQueryService;
import com.xjgzinfo.usdp.service.ImgAssetsService;
import com.xjgzinfo.usdp.service.dto.ImgAssetsCriteria;
import com.xjgzinfo.usdp.service.dto.ImgAssetsDTO;
import com.xjgzinfo.usdp.service.ext.ImgAssetsExtQueryService;
import com.xjgzinfo.usdp.web.util.HeaderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing {@link com.xjgzinfo.usdp.domain.ImgAssets}.
 */
@RestController
@RequestMapping("/blade-visual")
public class ImgAssetsResource {

    private static final String ENTITY_NAME = "AvueServer4jAppImgAssets";
    private final Logger log = LoggerFactory.getLogger(ImgAssetsResource.class);
    private final ImgAssetsService imgAssetsService;
    private final ImgAssetsQueryService imgAssetsQueryService;
    private final ImgAssetsExtQueryService imgAssetsExtQueryService;
    private final JwtDecoder jwtDecoder;
    @Value("${spring.application.name:usdp-app-unkown}")
    private String applicationName;

    public ImgAssetsResource(ImgAssetsService imgAssetsService, ImgAssetsQueryService imgAssetsQueryService, ImgAssetsExtQueryService imgAssetsExtQueryService, JwtDecoder jwtDecoder) {
        this.imgAssetsService = imgAssetsService;
        this.imgAssetsQueryService = imgAssetsQueryService;
        this.imgAssetsExtQueryService = imgAssetsExtQueryService;
        this.jwtDecoder = jwtDecoder;
    }

    /**
     * {@code POST  /img/save} : 创建实体 imgAssets.
     *
     * @param imgAssetsDTO the imgAssetsDTO to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new imgAssetsDTO, or with status {@code 400 (Bad Request)} if the imgAssets has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("/img/save")
    public ResponseResult<ImgAssetsDTO> createImgAssets(@Valid @RequestBody ImgAssetsDTO imgAssetsDTO) throws URISyntaxException {
        log.debug("REST request to save ImgAssets : {}", imgAssetsDTO);
        if (imgAssetsDTO.getId() != null) {
            return new ResponseResult(200, null, "ID已存在", false);
        }
        ImgAssetsDTO result = imgAssetsService.save(imgAssetsDTO);
        if (result.getId() != null) {
            return new ResponseResult(200, result, "创建成功", true);
        } else {
            return new ResponseResult(400, result, "创建失败", false);
        }
    }

    /**
     * {@code PUT  /img/update} : 修改实体 imgAssets.
     *
     * @param imgAssetsDTO the imgAssetsDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated imgAssetsDTO,
     * or with status {@code 400 (Bad Request)} if the imgAssetsDTO is not valid,
     * or with status {@code 500 (Internal Server Error)} if the imgAssetsDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("/img/update")
    public ResponseResult<ImgAssetsDTO> updateImgAssets(@Valid @RequestBody ImgAssetsDTO imgAssetsDTO) throws URISyntaxException {
        log.debug("REST request to update ImgAssets : {}", imgAssetsDTO);
        if (imgAssetsDTO.getId() == null) {
            return new ResponseResult(400, null, "ID不能为空", false);
        }
        ImgAssetsDTO result = imgAssetsService.save(imgAssetsDTO);
        return new ResponseResult(200, result, "修改成功", true);
    }

    /**
     * {@code GET  /img/all} : 获取全部实体 imgAssets.s
     *
     * @param criteria the criteria which the requested entities should match.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of imgAssets in body.
     */
    @GetMapping("/img/all")
    public ResponseResult<List<ImgAssetsDTO>> getPageImgAssets(ImgAssetsCriteria criteria) {
        log.debug("REST request to get ImgAssets by criteria: {}", criteria);
        BooleanFilter isPublicFilter = new BooleanFilter();
        isPublicFilter.setEquals(true);
        criteria.setIsPublic(isPublicFilter);
        List<ImgAssetsDTO> list = imgAssetsQueryService.findByCriteria(criteria);
        Optional<String> jwtOptions = SecurityUtils.getCurrentUserJWT();
        if (jwtOptions.isPresent()) {
            Jwt jwt = jwtDecoder.decode(jwtOptions.get());
            long userId = Long.valueOf(jwt.getClaims().get(AuthConstant.USERID_CLAIM).toString());
            ImgAssetsCriteria orCriteria = new ImgAssetsCriteria();
            LongFilter userIdFilter = new LongFilter();
            userIdFilter.setEquals(userId);
            orCriteria.setUserId(userIdFilter);
            list = imgAssetsExtQueryService.findByOrCriteria(criteria, orCriteria);
        }
        return new ResponseResult(200, list, "", true);
    }

    /**
     * {@code GET  /img/list} : 分页获取实体列表 imgAssets.
     *
     * @param criteria the criteria which the requested entities should match.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of imgAssets in body.
     */
    @GetMapping("/img/list")
    public ResponsePage<ImgAssetsDTO> getAllImgAssets(ImgAssetsCriteria criteria, Pageable pageable) {
        log.debug("REST request to get ImgAssets by criteria: {}", criteria);
        BooleanFilter isPublicFilter = new BooleanFilter();
        isPublicFilter.setEquals(true);
        criteria.setIsPublic(isPublicFilter);
        Page<ImgAssetsDTO> page = imgAssetsQueryService.findByCriteria(criteria, pageable);
        Optional<String> jwtOptions = SecurityUtils.getCurrentUserJWT();
        if (jwtOptions.isPresent()) {
            Jwt jwt = jwtDecoder.decode(jwtOptions.get());
            long userId = Long.valueOf(jwt.getClaims().get(AuthConstant.USERID_CLAIM).toString());
            ImgAssetsCriteria orCriteria = new ImgAssetsCriteria();
            LongFilter userIdFilter = new LongFilter();
            userIdFilter.setEquals(userId);
            orCriteria.setUserId(userIdFilter);
            page = imgAssetsExtQueryService.findAllByOrCriteria(criteria, orCriteria, pageable);
        }
        PageWapper<ImgAssetsDTO> pageWapper = new PageWapper(page.getNumber(), page.getTotalPages(), page.getContent(), page.getSize(), page.getTotalElements());
        return new ResponsePage(200, pageWapper, "", true);
    }

    /**
     * {@code GET  /img/count} : count all the imgAssets.
     *
     * @param criteria the criteria which the requested entities should match.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the count in body.
     */
    @GetMapping("/img/count")
    public ResponseEntity<Long> countImgAssets(ImgAssetsCriteria criteria) {
        log.debug("REST request to count ImgAssets by criteria: {}", criteria);
        return ResponseEntity.ok().body(imgAssetsQueryService.countByCriteria(criteria));
    }

    /**
     * {@code GET  /img/detail} : ID查询实体 imgAssets.
     *
     * @param id the id of the imgAssetsDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the imgAssetsDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/img/detail")
    public ResponseResult<ImgAssetsDTO> getImgAssets(@RequestParam Long id) {
        log.debug("REST request to get ImgAssets : {}", id);
        Optional<ImgAssetsDTO> imgAssetsDTO = imgAssetsService.findOne(id);
        if (imgAssetsDTO.isPresent()) {
            return new ResponseResult(200, imgAssetsDTO.get(), "", true);
        } else {
            return new ResponseResult(404, null, "未查询到数据", false);
        }
    }

    /**
     * {@code DELETE  /img/remove} : ID删除实体 imgAssets.
     *
     * @param id the id of the imgAssetsDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @PostMapping("/img/remove")
    public ResponseEntity<Void> deleteImgAssets(@RequestParam Long id) {
        log.debug("REST request to delete ImgAssets : {}", id);
        imgAssetsService.delete(id);
        return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build();
    }
}
